<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <link rel="stylesheet" href="/public/bootstrap.min.css">
  <link rel="stylesheet" href="/public/bootstrap-icons-141.css">
  <link rel="stylesheet" href="/public/style-light.css">
  
  <script src="/public/jquery.min.js"></script>
  <script src="/public/dayjs.min.js"></script>
  <script src="/public/bootstrap.bundle.min.js"></script>
  <script src="/public/util.js"></script>
  
  <title>Tags - localtags</title>
  <style>
    .Tag {
      cursor: pointer;
    }
  </style>
</head>
<body>
  <div id="root" class="container" style="max-width: 775px; min-width: 400px;"></div>
  <script>

const Alerts = CreateAlerts();

const [InfoBtn, InfoMsg] = CreateInfoPair('使用说明', m('ul').append([
  m('li').text('标签颜色是随机的，没有特殊含义。标签旁的数字表示与该标签关联的文件数。点击标签可找出与该便签有关的标签组。'),
  m('li').text('按 F12 进入控制台输入 deletetag("标签名") 可删除标签。注意：一旦删除无法恢复。'),
  m('li').text('如果删除标签可能导致一个文件完全没有标签，会提示删除失败，并返回文件 ID。'),
]));

const Navbar = {
  view: () => m('nav').addClass('navbar navbar-light bg-light').append([
    m('div').addClass('container-fluid').append([
      m('a').attr({title:'main menu',href:'/light/home',type:'button'}).addClass('btn btn-outline-dark').append(
        m('i').addClass('bi bi-house-door'),
      ),
      m('span').addClass('navbar-brand').append([
        'Tags', ' ', m(InfoBtn),
      ]),
      m('a').attr({title:'tag groups',href:'/light/tag-groups',type:'button'})
        .addClass('btn btn-outline-dark').append(
          m('i').addClass('bi bi-tags')
      ),
    ]),
  ]),
};

const ByDate = cc('input');
const SortByDate = cc('div');
SortByDate.prepend = (tag, index) => {
  const item = createTagItem(tag, index);
  $(SortByDate.id).prepend(m(item));
};

const ByName = cc('input');
const SortByName = cc('div');
SortByName.append = (tag, index) => {
  const item = createTagItem(tag, index);
  $(SortByName.id).append(m(item));
};

const SortBy = cc('div', null, [
  m('span').text('Sort by').css('margin-right', '1rem'),
  m('div').addClass('form-check form-check-inline').append([
    m(ByDate).attr({type:'radio',name:'sort-by',value:'by-date'})
        .addClass('form-check-input').prop('checked',true).click(() => {
          show(SortByDate.id);
          hide(SortByName.id);
        }),
    m('label').text('date').addClass('form-check-label').attr({for:ByDate.raw_id}),
  ]),
  m('div').addClass('form-check form-check-inline').append([
    m(ByName).attr({type:'radio',name:'sort-by',value:'by-name'})
        .addClass('form-check-input').click(() => {
          show(SortByName.id);
          hide(SortByDate.id);
        }),
    m('label').text('name').addClass('form-check-label').attr({for:ByName.raw_id}),
  ]),
]);

const TagCard = cc('div');
const TagCardName = cc('h3');
const TagCardBody = cc('div');
const TagCardAlerts = CreateAlerts();
const TagCardLoading = cc('div', null, [
  m('div').addClass('spinner-border').attr({role:'status'}).append(
    m('span').addClass('visually-hidden').text('Loading...')
  ),
]);
const TagCardTags = cc('div');

TagCard.view = () => m('div').attr({id:TagCard.raw_id,tagindex:'-1'})
  .addClass('offcanvas offcanvas-end text-break').append([
    m('div').addClass('offcanvas-header').append([
      m(TagCardName).addClass('offcanvas-title').text('ha ha ha'),
      m('button').attr({type:'button','data-bs-dismiss':'offcanvas'}).addClass('btn-close text-reset'),
    ]),
    m(TagCardBody).addClass('offcanvas-body').append([
      m(TagCardAlerts),
      m(TagCardLoading).addClass('text-center'),
      m(TagCardTags).addClass('Tags lh-lg'),
    ]),
]);

$('#root').append([
  m(Navbar).addClass('mt-2 mb-5'),
  m(InfoMsg).hide(),
  m(Alerts),
  m(Loading),
  m(SortBy).hide(),
  m(SortByDate).addClass('TagList d-flex flex-wrap mt-3'),
  m(SortByName).addClass('TagList d-flex flex-wrap mt-3'),
  m(TagCard),
  m(Spacer),
  m(BottomLine),
]);
  
init()

function init() {
  
  hide(SortByName.id);

  ajax({method:'GET',url:'/api/tags-by-date',alerts:Alerts},
      (tags) => {
        if (!tags || tags.length == 0) {
          Alerts.insert('info', '空');
          return;
        }
        $(SortBy.id).show();
        tags.forEach(SortByDate.prepend);
      }, null, () => {
        Loading.hide();
      });

  ajax({method:'GET',url:'/api/tags-by-name',alerts:Alerts},
      (tags) => {
        if (tags) {
          console.log('Tags: ');
          tags.forEach((tag, i) => {
            console.log(tag.ID);
            SortByName.append(tag, i);
          });
        }
      });

  $(TagCard.id).on('hidden.bs.offcanvas', () => {
    TagCardAlerts.clear();
  });
}

function createTagItem(tag, i) {
  const btnColor = buttonColors(i);
  const badgeColor = badgeColors(i);
  const tagLink = '/light/tag?name='+encodeURIComponent(tag.ID);
  const self = cc('a', 't'+tag.ID);

  self.view = () => m('button').addClass(`btn btn-${btnColor} mx-1 my-1`)
    .attr({
      type:'button', 'data-bs-toggle':'offcanvas', 'data-bs-target':TagCard.id,
    }).append([
      tag.ID, ' ',
      m('span').text(tag.Count).addClass(`badge bg-light text-dark`),
    ]).click(() => {
      $(TagCardName.id).text(tag.ID);
      $(TagCardTags.id).html('');

      const body = new FormData();
      body.append('name', tag.ID);  
      ajax({method:'POST',url:'/api/get-groups-by-tag',alerts:TagCardAlerts,body:body},
        (groups) => {
          if (!groups || groups.length == 0) {
            groups = [[tag.ID]];
          }
          const tag_set = new Set();
          groups.forEach(group => {
            group.forEach(tag => { tag_set.add(tag) });
          });
          tag_set.forEach(name => {
            const tagItem = cc('a');
            const tagLink = '/light/tag-preview?tags=' + encodeURIComponent([tag.ID, name]);
            $(TagCardTags.id).append(
              m(tagItem).text('#'+name).addClass('Tag').click(() => {
                window.open(tagLink, null, 'left=50,top=50,innerWidth=750,innerHeight=500,scrollbars');
              })
            );
            if (name == tag.ID) {
              const tagLink = '/light/tag?name=' + encodeURIComponent(name);
              $(tagItem.id).addClass('link-success').off().click(() => {
                window.open(tagLink, null, 'left=50,top=50,innerWidth=750,innerHeight=500,scrollbars');
              });
            }
          });
        }, null, () => {
          $(TagCardLoading.id).hide();
        });
    });
  
  return self;
}

function buttonColors(i) {
  const colors = ['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'dark'];
  return colors[i % colors.length];
}

function badgeColors(i) {
  const colors = ['secondary', 'success', 'danger', 'dark', 'primary'];
  return colors[i % colors.length];
}

function deletetag(name) {
  const body = new FormData();
  body.append('tag-name', name);
  ajax({method:'POST',url:'/api/delete-tag',body:body},
      () => {
        console.log('已删除 #' + name);
      });
}

  </script>
</body>
</html>